package com.castudio.Controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.castudio.COS.qiniu.service.QiNiuService;
import com.castudio.Common.RespPageEntity;
import com.castudio.Entity.Dto.UpdateR;
import com.castudio.Entity.Repairtable;
import com.castudio.Filter.R;
import com.castudio.Filter.Result;
import com.castudio.Service.RepairtableService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 小陈同学
 * @since 2022-12-14
 */
@Slf4j
@RestController
@RequestMapping("/repairtable")
public class RepairtableController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private RepairtableService repairtableService;

    /*@Resource
    private COSConfig COSConfig;*/

    @Autowired
    private QiNiuService qiNiuService;


    @GetMapping("/all")
    public List<Repairtable> listAll() {

        return repairtableService.list();

    }

    /*新增*/
    @PostMapping("/add")
    public boolean add(@RequestBody Repairtable reairtable) {

        return repairtableService.save(reairtable);

    }

    /*更新*/
    @PostMapping("/update")
    public boolean update(@RequestBody Repairtable reairtable) {

        return repairtableService.updateById(reairtable);

    }

    /**
     * 新增或更新
     * 所有的操作都要获取到id
     */
    @PostMapping("/AddOrUpdate")
    public Result AddOrUpdate(@RequestBody Repairtable reairtable) {

        return repairtableService.saveOrUpdate(reairtable) ? Result.success() : Result.failure();

    }

    /*删除*/
    @GetMapping("/delete")
    public boolean delete(Integer id) {

        return repairtableService.removeById(id);

    }

    /**
     * web分页
     */
    /*@GetMapping("/{currentPage}/{PageSize}")
    public RespPageEntity listPage(@RequestParam(defaultValue = "1")Integer page,
                                   @RequestParam(defaultValue = "20") Integer size){
        return repairtableService.getAllPage(page,size);
    }*/
    @GetMapping("/{currentPage}/{PageSize}")
    public R getPage(@PathVariable Integer currentPage, @PathVariable Integer PageSize, Repairtable reairtable){
        IPage<Repairtable> page = repairtableService.getPage(currentPage,PageSize,reairtable );
        //如果当前页码之大于总页码值，重新执行查询操作，使用最大页码作为当前页码值
        if (currentPage > page.getPages())//如果当前页码之大于总页码值
            page = repairtableService.getPage((int)page.getPages(),PageSize);//使用最大页码作为当前页码值
        return new R(true,page);
    }

    /**
     * 小程序分页，主要用于历史订单
     * openid作为唯一值
     */
    @PostMapping("/Page")
    public RespPageEntity Page(@RequestParam(defaultValue = "1") Integer page,
                               @RequestParam(defaultValue = "20") Integer size,
                               @RequestParam(defaultValue = "") String openid) {
        return repairtableService.page(page, size, openid);
    }

    /**
     * 维修图片上传+表单上传
     * 注：前端图片要求上传，图片没有上传将会返回错误code=400
     */
    @ApiOperation(value = "上传文件,form-data当时,传值file", notes = "上传文件,form-data方式,传值file")
    @PostMapping("/uploadFile")
    public JSONObject uploadFile(HttpServletRequest req, HttpServletResponse res) {

        JSONObject data = new JSONObject();
        try {
            MultipartHttpServletRequest mreq = (MultipartHttpServletRequest) req;
            MultipartFile image = mreq.getFile("image");
            if (image.getSize() > 0) {
                String path = "/CAStudio";
                InputStream inputStream = image.getInputStream();
                //String fileUrl = COSConfig.uploadFile(image, path, req.getServletContext());
                String fileUrl = qiNiuService.uploadFile(inputStream, path);

                /*前端获取数据*/
                String openid = req.getParameter("openid");
                String time = req.getParameter("time");
                String realname = req.getParameter("realname");
                String stunum = req.getParameter("stunum");
                String dormnum = req.getParameter("dormnum");
                String phone = req.getParameter("phone");
                String computername = req.getParameter("computername");
                String computertype = req.getParameter("computertype");
                String reason = req.getParameter("reason");

                data.put("code", 200);
                data.put("msg", "上传成功");
                data.put("fileUrl", fileUrl);

                System.out.println(openid);
                System.out.println(fileUrl);
                System.out.println(realname);
                System.out.println(stunum);
                System.out.println(dormnum);
                System.out.println(phone);
                System.out.println(computername);
                System.out.println(computertype);
                System.out.println(reason);
                System.out.println(time);

                repairtableService.save(fileUrl, computertype, computername, reason, realname, stunum, dormnum, phone, time, openid);

                return data;
            } else {
                data.put("code", 400);
                data.put("msg", "请上传文件");
                return data;
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            data.put("code", 500);
            data.put("msg", "网络开小差了");
            return data;
        }

    }

    /**
     * 当维修人员点击接单按钮后
     * 1.维修人员携带自己openid进来
     * 2.点击接单后，openid对应repairid，接单时间对应updatetime
     * 3.执行更新操作
     * 4.执行更新操作需要把该订单的id传进来
     * 5.通过id来作为唯一凭证的更新
     */
    @PostMapping("/updateR")
    public String updateR(@RequestBody UpdateR r) {
        return repairtableService.updateR(r);
    }

    /**
     * 当维修人员完成维修后点击完成按钮
     * 1.点击完成按钮后
     * 2.系统自动变更state值为1
     * 3.获得当前的时间
     * 4.获取小程序端备注
     */
    @PostMapping("/updateS")
    public String updateS(@RequestBody UpdateR r) {
        return repairtableService.updateS(r);
    }

}
